<%@page import="fr.vahren.sriksal.controller.bean.MapTile.Elevation"%>
<%@page import="fr.vahren.sriksal.controller.bean.MapTile.Biome"%>
<%@page import="fr.vahren.sriksal.controller.bean.MapTile"%>
<%@page import="java.util.ArrayList"%>
<%
	MapTile[][] map = (MapTile[][])session.getAttribute("map");
%>



<div id="map">
	<canvas id="canvas" width="500" height="500">
 Your browser does not support HTML5 Canvas.
</canvas>
	<aside id="tile">
		<span class="tile_info_title">Tile info:</span><br/> <span
			class="tile_info">ID:</span><span id="tile_id"></span><br/> <span
			class="tile_info">Elevation:</span><span id="tile_elevation"></span><br/>
		<span class="tile_info">Biome:</span><span id="tile_biome"></span><br/> <span
			class="tile_info">Has a town:</span><span id="tile_town"></span><br/>
		<button onclick="javascript:addTown()" class="actionButton">Place
			a town here</button>
	</aside>
</div>

<script type="text/javascript">
	
	
	var context;
	var theCanvas;

	// CONSTANTS
	var mapRows = 10;
	var mapCols = 10;
	var tileSheetWidth = 6;
	var tileW = 50;
	var tileH = 50;
	var toolTipW = 150;
	var toolTipH = 100;
	var canvasW = 500;

	// VARIABLES
	var tileSheet = new Image();
	var tileSheetLoaded = false;
	var townSheet = new Image();
	var townSheetLoaded = false;

	var map;
	
	var biomes = [ <% for(int i =0;i<Biome.values().length;i++){ out.print("'"+Biome.values()[i].toString()+"'"); if(i!=Biome.values().length-1){out.print(",");} }%> ];
	var elevations = [ <% for(int i =0;i<Elevation.values().length;i++){ out.print("'"+Elevation.values()[i].toString()+"'"); if(i!=Elevation.values().length-1){out.print(",");} }%> ];
	
	var selectedTileX;
	var selectedTileY;
	
	window.addEventListener('load', eventWindowLoaded, false);
	function eventWindowLoaded() {
	   canvasApp();
	}

	function canvasApp(){
	      theCanvas = document.getElementById("canvas");
	      context = theCanvas.getContext("2d");

	      initListeners();
	      loadMap();
	      
	}
	
	function loadMap(){
		getMap(drawMap);
	}
	
	function drawMap(){
		tileSheet.addEventListener('load', function(){eventSheetLoaded('tile');} , false);
		tileSheet.src = "/static/images/mapTiles.png";
		townSheet.addEventListener('load', function(){eventSheetLoaded('town');} , false);
		townSheet.src = "/static/images/town_smaal.png";
	}

	function eventSheetLoaded(sheet) {
		if(sheet == 'tile'){
			tileSheetLoaded = true;
		}else if(sheet == 'town'){
			townSheetLoaded = true;
		}
		
		if(tileSheetLoaded && townSheetLoaded){
			drawScreen();
		}
	}
	

	// MAIN DRAWING FUNCTION
	function drawScreen() {
		for ( var i = 0; i < map.length; i++) {
			for ( var j = 0; j < map[i].length; j++) {
				drawBaseTile(i,j);
				drawTowns(i,j);
				drawAroundTile(selectedTileX,selectedTileY);
			}
		}
	}
	
	function drawBaseTile(i,j){
		var sourceTileId = getIndex(map[i][j].biome,biomes)*3+getIndex(map[i][j].elevation,elevations);
        var sourceX = Math.floor(sourceTileId % tileSheetWidth) *tileW;
        var sourceY = Math.floor(sourceTileId / tileSheetWidth) *tileH;
        context.drawImage(tileSheet, sourceX,sourceY,tileW,tileH,i*tileW,j*tileH,tileW,tileH);
	}
	
	function drawTowns(i,j){
		if(map[i][j].hasTown){
			context.drawImage(townSheet, 0,0,38,38,i*tileW+5,j*tileH+5,38,38);
		}
	}
	

	function tile(biome, elevation, id, hasTown) {
		this.biome = biome;
		this.elevation = elevation;
		this.id = id;
		this.hasTown = hasTown;
	}
	

	// mouse event managing
	function initListeners() {
		theCanvas.addEventListener('mousemove', onMouseMove, 0);
		theCanvas.addEventListener('mouseout', onMouseOut, 0);
		theCanvas.addEventListener('mouseup', onMouseUp, 0);
	}

	function onMouseMove(e) {
		drawScreen();
		
		var x = e.pageX - theCanvas.offsetLeft;
		var y = e.pageY - theCanvas.offsetTop;
		
		// Get the corresponding tile
		var tile = getTile(x,y);
		drawAroundTile(Math.floor(x/tileW),Math.floor(y/tileH));

		var str = getTileDescription(tile);
		
		var xDelta, yDelta;
		if(x+toolTipW > canvasW){// trop a droite
			xDelta = -(toolTipW+10);
		}else{
			xDelta = 10;
		}
		if(y - toolTipH < 0){//trop haut
			yDelta = 10;
		}else{
			yDelta = -(toolTipH + 10);
		}

		context.fillStyle = '#603f3f';
		context.fillRect(x + xDelta, y + yDelta, toolTipW, toolTipH);
		context.fillStyle = '#fff';
		context.font = 'bold 20px verdana';
		context.fillText(str, x + xDelta + 5, y + yDelta +25, toolTipW-10);

	}
	
	function drawAroundTile(x,y){
		if(selectedTileX != undefined && selectedTileY != undefined){
			drawTileRect(selectedTileX,selectedTileY,4,'red');
		}else{
			drawTileRect(x,y,4,'red');
		}
	}
	
	function drawTileRect(x,y,thickness,color){
		var xP = x*tileW;
		var yP = y*tileH;
		context.beginPath();
		context.rect(xP,yP, tileW, tileH);
	      context.lineWidth = thickness;
	      context.strokeStyle = color;
	      context.stroke();
	}
	
	function onMouseOut(e){
		drawScreen();
		drawAroundTile(0);
	}
	
	function onMouseUp(e){
		var x = e.pageX - theCanvas.offsetLeft;
		var y = e.pageY - theCanvas.offsetTop;
		var dX = Math.floor(x/tileW);
		var dY = Math.floor(y/tileH);
		// Get the corresponding tile
		var tile = getTile(x,y);
		
		if(selectedTileX != undefined &&  selectedTileX == dX 
				&& selectedTileY != undefined &&  selectedTileY == dY){
			deselect();
		}else{
			select(tile,dX,dY);
		}
		
		
	}
	
	// TILE MANAGING
	function getTile(x,y){
		var xT = Math.floor(x/tileW);
		var yT = Math.floor(y/tileH);
		return map[xT][yT];
	}
	
	function getTileDescription(tile){
		return tile.biome + " ELEVATION : "+tile.elevation + (tile.hasTown?" TOWN":"");
	}
	
	function deselect(){
		selectedTileX = undefined;
		selectedTileY = undefined;
		// display informations about the tile in the right.
		setText('tile_id','');
		setText('tile_elevation','');
		setText('tile_biome','');
		setText('tile_town','');
	}
	
	function select(tile,x,y){
		selectedTileX = x;
		selectedTileY = y;
		// display informations about the tile in the right.
		refreshInfo(tile);
	}
	
	function refreshInfo(tile){
		console.log('refresh '+tile);
		setText('tile_id',tile.id);
		setText('tile_elevation',tile.elevation);
		setText('tile_biome',tile.biome);
		setText('tile_town',tile.hasTown);
	}
	
	function addTown(){
		if(selectedTileX!=undefined && selectedTileY!=undefined){
			requestJSON('game/addTown?x='+selectedTileX+'&y='+selectedTileY,function(res){
				getMap(drawScreen);
			});
		}
	}
	
	// SERVER COM
	function getMap(onFinished){
		requestJSON('game/retrieveMap',function(res){
				map = JSON.parse(res).map;
				if(selectedTileX!=undefined && selectedTileY!=undefined){
					refreshInfo(map[selectedTileX][selectedTileY]);
				}
				onFinished();
		});
	}
	
	
	function getIndex(item,list){
		for(var i = 0;i<list.length;i++){
			if(list[i] === item){
				return i;
			}
		}
		return -1;
	}
</script>
